package cn.wolfcode.job;

import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.redis.SeckillRedisKey;
import cn.wolfcode.web.feign.ISeckillProductFeignService;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 任务类,周期性从数据查询出秒杀商品列表的数据到redis中
 */
@Component
public class SeckillProductCacheJob implements SimpleJob {
    @Autowired
    private ISeckillProductFeignService seckillProductFeignService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void execute(ShardingContext shardingContext) {
        Integer time = Integer.parseInt(shardingContext.getShardingParameter());
        // 查询当前的秒杀商品的数据
        Result<List<SeckillProductVo>> result = seckillProductFeignService.queryByTimeForJob(time);
        if (result == null || result.hasError()) {
            // 通知管理员，定时任务没有执行成功
            return;
        }
        List<SeckillProductVo> seckillProductVos = result.getData();
        // 将之前redis的数据删除
        String seckillProductHashKey = SeckillRedisKey.SECKILL_PRODUCT_HASH.getRealKey(time + "");
        // 秒杀商品库存的key
        String stockCountHashKey = SeckillRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(time + "");
        redisTemplate.delete(seckillProductHashKey);
        redisTemplate.delete(stockCountHashKey);
        // 将查询到的数据设置Hash的数据结构中
        for (SeckillProductVo seckillProductVo : seckillProductVos) {
            redisTemplate.opsForHash().put(seckillProductHashKey,seckillProductVo.getId().toString(), JSON.toJSONString(seckillProductVo));
            // 存储指定每个秒杀商品的库存数量存储到redis中
            redisTemplate.opsForHash().put(stockCountHashKey,seckillProductVo.getId()+"",seckillProductVo.getStockCount()+"");

        }
        System.out.println("初始化完成");

    }
}
